<template>
  <div>
    <t-dialog :show="dialogVisible" @hide="() => {
      dialogVisible = false;
    }
      " @show="() => {
        dialogVisible = true;
      }
        " class="RtAddPortletHelper RtEditorPortletHelper" position="right" :maximized="true" ref="drawer"
      style="max-width: 100%">
      <div :style="($q.screen.xs || $q.platform.is.mobile) ? 'width:100vw' : 'width: 400px'">
        <div class="header">
          <p class="title">
            {{ title }}
          </p>
          <p class="operate">

            <i class="fas dx-icon icon-t-delete-01" style="font-size: 14px;color: rgba(0,0,0,.9);"
              @click="dialogVisible = false; visiblePortletsPreview = false;"></i>
          </p>
        </div>
        <div class="listContent">
          <t-list padding bordered class="rounded-borders">
            <t-expansion-item dense dense-toggle expand-separator :label="$q.lang.portal.portalSetting" default-opened>
              <t-card>
                <t-card-section>
                  <t-input textAlign='left' borderType='borderless' :label="$q.lang.portal.title" labelPosition="top"
                    v-model="Title" class='tr-input-form'></t-input>
                  <t-toggle v-if="portalInstance?.PortletCategory != 'metrics'" labelPosition="top"
                    :label="$q.lang.portal.showRefresh" v-model="IsShowRefreshButton" />
                  <t-toggle labelPosition="top" :label="$q.lang.portal.isAutoRefresh" v-model="IsAutoRefresh" />
                  <t-input class='tr-input-form' textAlign='left' borderType='borderless' v-if="IsAutoRefresh"
                    :label="$q.lang.portal.refreshInterval" labelPosition="top" v-model="RefreshInterval"></t-input>
                </t-card-section>
              </t-card>
            </t-expansion-item>

            <t-expansion-item dense dense-toggle expand-separator :label="$q.lang.portal.operateSetting" default-opened>
              <t-card>
                <t-card-section>
                  <UI_MetricsSet @setTitle="setTitle" ref="UI_MetricsSet" 
                    v-if="computedInparams.some(i => i.Code == 'StaticMetricsFilters' || i.Code == 'MetricsConfig' || i.Code == 'MetricsFilters')" :PortletBusinessType="PortletBusinessType">
                  </UI_MetricsSet>
                  <p v-for="i in computedInparams">
                    <span
                      v-if="i.Code == 'StaticMetricsFilters' || i.Code == 'MetricsConfig' || i.Code == 'MetricsFilters'||i.Code=='SpecialFilters'">

                    </span>
                    <span v-else-if='i.PublicParamsSetting'>
                    </span>
                    <t-input  v-else-if="i.variableInputType == '0'" style="width: 100%" borderless v-bind="i.bind"
                      v-on="i.on" class="tr-input-form" :label="i.label" labelPosition="top" textAlign='left'
                      borderType='borderless'>
                    </t-input>
                    <t-select textAlign='left' borderType='borderless' v-else style="width: 100%" borderless
                      v-bind="i.bind" v-on="i.on" class="tr-input-form tr-input-editform" :label="i.label" labelPosition="top"
                      itemsDataSourceType="static" :staticItems="computedOutParams"></t-select>
                  </p>
                </t-card-section>
              </t-card>
            </t-expansion-item>
          </t-list>
        </div>
        <p class="buttonOperate">
          <t-button @click="
            dialogVisible = false;
          visiblePortletsPreview = false;
          " style="
              color: rgba(0, 0, 0, var(--t-color-opacity, /*批量处理90%透明度*/0.9));
              border: 1px solid #dcdcdc;
              padding: 8px 6px;
            ">{{ Terms.portal.cancel }}</t-button>
          <t-button type="primary" @click="sureData" class="tr-button-primary">{{ Terms.portal.confirm }}</t-button>
        </p>
      </div>
    </t-dialog>
  </div>
</template>

<script>
import TDialog from 't/basic/dialog';
import TButton from 't/basic/button';
import TList from 't/basic/list';
import TExpansionItem from 't/basic/expansion-item';
import TCard from 't/basic/card';
import TCardSection from 't/basic/card/CardSection';
import TCardActions from 't/basic/card/CardActions';
import TInput from 't/basic/input';
import TToggle from 't/basic/toggle';
import TSelect from 't/basic/select'

import _ from 'lodash';
import { Terms } from './lib/Term';
export default {
  data() {
    return {
      Terms: Terms,
      title: Terms.addPortal.editTitle,
      dialogVisible: false,
      updateInparamsList: [],
      RefreshInterval: 0,
      Title: '',
      IsShowRefreshButton: false,
      IsAutoRefresh: false,

      targetParent: {},
      target: {},
      template: JSON.stringify({
        "MetricsMetadataID": "",
        "MetricsMetadataName": "",
        "IsSubTitleSameWithMetrics": true,
        "SubTitle": "",
        "IsSubDescWithMetrics": true,
        "SubDesc": "",
        "EnableMetricsDataLink": false,
        "MetricsDataLinkAddress": "",
        "EnableMetricsToDo": "",
        "MetricsToDoAddress": "",
        "MetadataOrder": 0,
        "MetricsDatasources": []
      }),
      isNotInit: true

    };
  },
  props: {
    args: {
      type: Object,
    },
    portalParamsInstance: Object,
    currenctInstanceCode: String,
    portalInstance: Object,
    localvars: Object,
  },
  components: {
    TDialog,
    TButton,
    TList,
    TExpansionItem,
    TCard,
    TCardSection,
    TCardActions,
    TInput,
    TToggle,
    TSelect
  },
  computed: {
    PortletBusinessType(){
      if(!this.portalParamsInstance[this.currenctInstanceCode]?.ins.hasOwnProperty('PortletBusinessType')){
        return this.portalParamsInstance[this.currenctInstanceCode]?.ins.Ext1.indexOf('TableMetrics')!=-1?2:0
      }else{
        return this.portalParamsInstance[this.currenctInstanceCode].ins.PortletBusinessType
      }
      
    },
   
    computedOutParams() {
      let res = [];
      let portalParamsInstance = _.cloneDeep(this.portalParamsInstance);
      for (let i in portalParamsInstance) {
        if (i != this.currenctInstanceCode) {
          if (portalParamsInstance[i].outParams) {
            portalParamsInstance[i].detail.outParams.forEach(j => {
              res.push({
                instanceCode: i,
                label: portalParamsInstance[i].ins.Title + '-' + j.Name,
                value: `_generateCode_outParams_${i}&&${j.Code}`,
              });
            });
          }
        }

      }
      if (this.localvars) {
        for (let i in this.localvars) {
          if (i != 'PublicParams') {
            res.push({
              instanceCode: i,
              label: `LocalVars.${i}`,
              value: `LocalVars.${i}`,
            });
          }

        }
      }
      return res;
    },
    computedInparams() {
      let res = [];
      let portalParamsInstance = this.portalParamsInstance
      if (portalParamsInstance[this.currenctInstanceCode].detail.inParams) {
        portalParamsInstance[this.currenctInstanceCode].detail.inParams.forEach(j => {
          try {
            //if (portalParamsInstance[this.currenctInstanceCode].inParams[j.Code] && portalParamsInstance[this.currenctInstanceCode].inParams[j.Code].indexOf('_generateCode_outParams_') > -1) {
            this.updateInparams(this.currenctInstanceCode, j.Code, j.ParamValue || j.DefaultValue);
            //  }
          } catch (error) {

          }
          portalParamsInstance[this.currenctInstanceCode].inParams[j.Code] = j.ParamValue || j.DefaultValue
          if (j.DefaultValue && j.DefaultValue.indexOf('LocalVars.PublicParams.') == 0) {

          } else {
            if (portalParamsInstance[this.currenctInstanceCode].inParams[j.Code] && typeof portalParamsInstance[this.currenctInstanceCode].inParams[j.Code] != 'string') {
              try {
                portalParamsInstance[this.currenctInstanceCode].inParams[j.Code] = JSON.stringify(portalParamsInstance[this.currenctInstanceCode].inParams[j.Code])
              } catch (error) {

              }
            }
            res.push({
              instanceCode: this.currenctInstanceCode,
              label: portalParamsInstance[this.currenctInstanceCode].ins.Title ? portalParamsInstance[this.currenctInstanceCode].ins.Title + '-' + j.Name : j.Name,
              variableInputType: j.VariableInputType,
              Code: j.Code,
              PublicParamsSetting: j.PublicParamsSetting,
              DefaultValue: portalParamsInstance[this.currenctInstanceCode].inParams[j.Code],
              bind: {
                modelValue: portalParamsInstance[this.currenctInstanceCode].inParams[j.Code],
                value: portalParamsInstance[this.currenctInstanceCode].inParams[j.Code],
              },
              on: {
                'update:modelValue': e => {
                  this.updateInparams(this.currenctInstanceCode, j.Code, e);
                  this.portalParamsInstance[this.currenctInstanceCode].detail.inParams.forEach(jj => {
                    if (jj.Code == j.Code) {
                      jj.ParamValue = e
                    }
                  })

                },
                'update:value': e => {
                  this.updateInparams(this.currenctInstanceCode, j.Code, e);

                  this.portalParamsInstance[this.currenctInstanceCode].detail.inParams.forEach(jj => {
                    if (jj.Code == j.Code) {
                      jj.ParamValue = e
                    }
                  })
                },
              },

              bindCode: j.Code,
            });
          }
        });
      }

      return res;
    },

  },
  mounted() {
    Funcs.LoadUmdComponent('UI_MetricsSet').then(res => {
      this.$nextTick(() => {
        this.init();
      })
    })

  },
  methods: {
    setTitle(e){
      !this.Title&&(this.Title=e)
    },
    init() {
      if (this.$refs.UI_MetricsSet) {
        let portalParamsInstance = this.portalParamsInstance
        if (portalParamsInstance[this.currenctInstanceCode].detail.inParams) {
          let StaticMetricsFilter = portalParamsInstance[this.currenctInstanceCode].detail.inParams.find(item => item.Code == 'StaticMetricsFilters')
          let MetricsConfig = portalParamsInstance[this.currenctInstanceCode].detail.inParams.find(item => item.Code == 'MetricsConfig')
          if (MetricsConfig) {
            let MetricsConfigData = {}

            try {
              MetricsConfigData = eval(MetricsConfig.ParamValue || MetricsConfig.DefaultValue)
            } catch (error) {
              try {
                MetricsConfigData = JSON.parse(MetricsConfig.ParamValue || MetricsConfig.DefaultValue)
              } catch (error) {
              }
            }
            this.$refs.UI_MetricsSet.setMetricsConfig(MetricsConfigData)
          }
          if (StaticMetricsFilter) {
            let StaticMetricsFilterData = {}
            try {
              StaticMetricsFilterData = eval(StaticMetricsFilter.ParamValue || StaticMetricsFilter.DefaultValue)
            } catch (error) {
              try {
                StaticMetricsFilterData = JSON.parse(StaticMetricsFilter.ParamValue || StaticMetricsFilter.DefaultValue)
              } catch (error) {
              }
            }

            this.$refs.UI_MetricsSet.setStaticMetricsFilters(StaticMetricsFilterData)
          }


        }
      }
    },
    updateInparams(instanceCode, code, value) {
      this.updateInparamsList = this.updateInparamsList.filter(
        item => item.code !== code
      );
      this.updateInparamsList.push({
        instanceCode: instanceCode,
        code: code,
        value: value,
      });

    },
    open: async function (cus) {
      this.dialogVisible = true;
    },

    sureData: async function () {
      if (this.RefreshInterval) {
        this.RefreshInterval = this.RefreshInterval.toString().replace(/ /ig, '')
      }
      if (this.IsAutoRefresh && (!this.RefreshInterval||this.RefreshInterval<0)) {
        Funcs.Notify(
          Terms.message.warn,
          this.$q.lang.portal.refreshIntervalWarning,
          'warning',
        );
        return;
      }
      if (this.$refs.UI_MetricsSet) {
        let MetricsConfig = this.$refs.UI_MetricsSet.getMetricsConfig()
        if (MetricsConfig) {
        
          if (!MetricsConfig.MetricsMetadatas||MetricsConfig.MetricsMetadatas.length == 0) {
            return 
          }
        } else {
          return 
        }
        let StaticMetricsFilter = this.$refs.UI_MetricsSet.getStaticMetricsFilters()
        if (MetricsConfig) {
          MetricsConfig.MainTitle = this.Title
        }
        this.updateInparams(this.currenctInstanceCode, 'MetricsConfig', MetricsConfig)
        this.updateInparams(this.currenctInstanceCode, 'StaticMetricsFilters', StaticMetricsFilter)
      }

      this.$emit('sureData', {
        updateInparamsList: this.updateInparamsList,
        portalInstance: {
          Title: this.Title,
          IsShowRefreshButton: this.IsShowRefreshButton,
          IsAutoRefresh: this.IsAutoRefresh,
          RefreshInterval: this.RefreshInterval,
          InstanceCode: this.currenctInstanceCode
        },

      });
      this.dialogVisible = false;
    },
  },
  watch: {
    dialogVisible(val) {
      if (val && this.isNotInit) {
        this.isNotInit = false
        this.init();
      }
    },
    portalInstance: {
      handler: function (val, oldVal) {
        if (val) {
          this.RefreshInterval = val.RefreshInterval;
          this.Title = val.Title;
          this.IsShowRefreshButton = val.IsShowRefreshButton;
          this.IsAutoRefresh = val.IsAutoRefresh;
        } else {
          this.RefreshInterval = 0;
          this.Title = '';
          this.IsShowRefreshButton = false;
          this.IsAutoRefresh = false;
        }
        this.$nextTick(() => {
          this.init();
        })
      },
      deep: true,
    }
  },
};
</script>
<style lang="scss">
.RtEditorPortletHelper {
  .q-list {
    padding: 0;
  }
header{
  .title{
    font-size:16px !important;
  }
}
  .q-item--dense {
    padding: 2px 20px;
    background: #f0f2f5 !important;
    min-height: 36px;
  }

  .q-expansion-item--expanded {}

  .q-card__section {
    padding: 0 20px;
    padding-bottom: 16px;
  }

  .q-card__section>div {
    margin-top: 8px;
  }

  .q-card__section>p>div {
    margin-top: 8px;
  }

  .q-list--bordered {
    border: 0;
  }

  .buttonOperate {
    display: flex;
    gap: 12px;
    padding: 10px !important;
    align-items: center;
    justify-content: end;
    width: 100%;
    margin: 0;
  }

  .listContent {
    width: 100%;
    height: calc(100vh - 102px);
    overflow: auto
  }
}

@media (max-width: 767px) {

  /* 这里放置当屏幕尺寸小于768px时的CSS规则 */
  .RtEditorPortletHelper {
    button {
      width: 50% !important;
      height: 40px;
    }

    .listContent {
      width: 100%;
      height: calc(100vh - 112px);
      overflow: auto
    }
  }
}
</style>
